package com.zhaopin.leetcode;

/**
 * @author Administrator
 * @create 2020-07-17 15:41
 */
public class Two {

    public static void main(String[] args) {
        ListNode a = new ListNode(2);
        ListNode b = new ListNode(4);
        ListNode c = new ListNode(3);

        ListNode x = new ListNode(5);
        ListNode y = new ListNode(6);
        ListNode z = new ListNode(4);

        a.next = b;
        b.next = c;

        x.next = y;
        y.next = z;

        System.out.println(addTwoNumbers(a,x));

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode retListNode = new ListNode(0);
        ListNode p=l1, q=l2, tmpListNode=retListNode;

        int tmpVal = 0;
        while (null != p || null != q){
            int pVal = (p != null) ? p.val : 0;
            int qVal = (q != null) ? q.val : 0;
            int sum = tmpVal + pVal + qVal;
            // 拿到要进位的值
            tmpVal = sum / 10;
            // 拿到留在该位的值
            tmpListNode.next = new ListNode(sum % 10);
            tmpListNode = tmpListNode.next;
            //判断非空继续指向
            if(null != p){
                p = p.next;
            }
            if(null != q){
               q = q.next;
            }
        }

        //最后判断如果进位的值大于0则再进位
        if(tmpVal > 0){
            tmpListNode.next = new ListNode(tmpVal);
        }
        return retListNode.next;
    }
}
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }//构造函数

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}



